package org.csu.sei.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
//import com.sun.tools.sjavac.Log;
import org.csu.sei.entity.User;
import org.csu.sei.util.interceptor.TEACHERInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import com.focuxin.model.User;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class TokenUtil {
    private static final long EXPIRE_TIME = 7*24*60*60*1000;//设置过期时间（这里单位是毫秒）7天
    private static final long SHORT_TIME = 10*60*1000;//10分钟
    private static final String User_SECRET = "testtoken";//私钥token_secret

    private static final Logger logger= LoggerFactory.getLogger(TEACHERInterceptor.class);

    public static String getUserToken(User User){
        //过期时间和加密算法设置
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(User_SECRET);//加密方式

        //头部信息
        Map<String,Object> header = new HashMap<>(2);
        header.put("typ","JWT");
        header.put("alg","HS256");
        System.out.println("userId"+User.getId()+"\n"+"userRole"+User.getRole());
        return JWT.create()
                .withIssuer("SEI")
                .withClaim("userId",User.getId())
                .withClaim("userRole",User.getRole())
                //最后一次登录时间有的话可以用
//                .withClaim("lastLogin",User.getLastLogin())
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public  static String getPasswordChangeToken(User user){
        //过期时间和加密算法设置
        Date date = new Date(System.currentTimeMillis()+SHORT_TIME);
        Algorithm algorithm = Algorithm.HMAC256(User_SECRET);//加密方式

        //头部信息
        Map<String,Object> header = new HashMap<>(2);
        header.put("typ","JWT");
        header.put("alg","HS256");
        System.out.println("userId"+user.getId()+"\n"+"userRole"+user.getRole());
        return JWT.create()
                .withIssuer("SEI")
                .withClaim("userId",user.getId())
                .withClaim("userRole",user.getRole())
                //最后一次登录时间有的话可以用
//                .withClaim("lastLogin",User.getLastLogin())
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static User getUserData(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(User_SECRET)).withIssuer("SEI").build();
        DecodedJWT jwt = verifier.verify(token);
        User user = new User();
        user.setId(jwt.getClaim("userId").asLong());
        user.setRole(jwt.getClaim("userRole").asInt());
//        user.setRole(jwt.getClaim("role").asString());
//        user.setLastLogin(jwt.getClaim("lastLogin").asDate());
        return user;
    }
    public static String creatToken(User user){
        //这里传入的是token对象，决定token的内容
        User tk = new User();
        Date date = new Date();
        tk.setId(user.getId());
        tk.setRole(user.getRole());
//        tk.setRole(role);
//        tk.setLastLogin(date);
        //交给上面实现类得到token
        return getUserToken(tk);
    }


    public String getUserDataOpenId(String User){
        return JWT.decode(User).getClaim("openid").asString();
    }
    public static boolean verify(String token){
        //通过JWT的验证机制是否报错区分是否成
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(User_SECRET)).withIssuer("SEI").build();
            DecodedJWT jwt = verifier.verify(token);
            
            //通过日志代替这段
//            System.out.println("认证通过：");
//            System.out.println("userId: " + jwt.getClaim("userId").asString());
//            System.out.println("过期时间：      " + jwt.getExpiresAt());
            logger.info("认证通过" + "userid: "+ jwt.getClaim("userId").asString() + "过期时间：  " + jwt.getExpiresAt());
            return true;
        } catch (Exception e){
            return false;
        }
    }

}